package com.example.app;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by lianghaiming on 16-1-22.
 */
public class ClientHandle extends Service {

    int command;

     private Socket socket = null;


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        new connectThread().start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    class handleThread extends Thread {

        InputStream input ;
        OutputStream output;
        DataInputStream din;

        public handleThread() {
            try {
                input = socket.getInputStream();
                din = new DataInputStream(input);
                output = socket.getOutputStream();
            }catch (IOException e){
                e.printStackTrace();
            }
        }

        @Override
        public void run() {
            try {
                output.write("connect success\n".getBytes("utf-8"));
                output.flush();
            }catch (IOException e ) {
                e.printStackTrace();
            }

            while(true) {
                try {
                    command = din.readInt();
                    String a = String.valueOf(command);

                    sendBroadcastOnCommand(command);
                    Log.d("liang", a);

                }catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    class connectThread extends Thread {

        @Override
        public void run() {


            try {
                ServerSocket serverSocket = new ServerSocket(1234);

                while(true){

                    socket = serverSocket.accept();

                    new handleThread().start();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }


    public void sendBroadcastOnCommand(int command) {
        Intent intent = new Intent(SingService.BROADCAST_MUSIC_CONTROL);
        intent.putExtra("command", command);
        sendBroadcast(intent);

    }

}
